package cn.stronglink.asset.message.mq.dam.handle;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.toolkit.IdWorker;

import cn.stronglink.asset.message.mq.dam.entity.IScreenCommandFactory;
import cn.stronglink.asset.message.mq.dam.entity.ScreenCommandEntity;
import cn.stronglink.asset.message.mq.dam.entity.dacai.UpdateArrayTextCommandFactory;
import cn.stronglink.asset.message.mq.dam.message.MQMessageOfDAM;
import cn.stronglink.asset.message.mq.topic.ReaderInfoSender;
import cn.stronglink.asset.model.DeviceType;
import cn.stronglink.asset.model.ItAsset;
import cn.stronglink.asset.module.assetmanage.itasset.vo.ItAssetVo;
import cn.stronglink.asset.module.dam.entity.dev.DeviceTypeVo;
import cn.stronglink.asset.module.dam.service.DamService;
import cn.stronglink.asset.module.dam.service.IDamService;
import cn.stronglink.suite.core.util.ByteUtil;
import cn.stronglink.suite.core.util.ContextUtils;

public class RackBindDeviceCodeHandle extends AbstractReturnExceptionHandle{
	protected final static String TOPIC_NAME = "serviceToDam";
	protected final static String ACTION_CODE = "screenRequest";
	protected final static String SEND_ACTION_CODE= "screenCommand";
	protected IDamService damService =(DamService)ContextUtils.getBean("sensorService");
	private ReaderInfoSender topicSender = (ReaderInfoSender) ContextUtils.getBean("readerInfoSender");
	
	private boolean isClickBtn;
	private boolean isReceiveRackName;
	private boolean isReceiveDamDeviceCode;
	private boolean isReceiveCollectionDevice1Code;
	private boolean isReceiveCollectionDevice2Code;
	
	private String rackName;
	private String damDeviceCode;
	private String collectionDevice1Code;
	private String collectionDevice2Code;
	
	private final static long MAX_TIME = 3000;
	private long lastReceiveTime = 0;
	
	private final static short DIALOG_ID = 1;
	private final static short DIALOG_SCREEN_ID = 9;
	
	@Override
	public boolean isHandle(MQMessageOfDAM msg) {
		ScreenCommandEntity entity = (ScreenCommandEntity) msg.getAwsPostdata();
		if(entity!=null) {
			if(entity.getCommand().equals("EEB1110008000D100100")
					||entity.getCommand().indexOf("EEB1110008000411")==0
					||entity.getCommand().indexOf("EEB1110008000611")==0
					||entity.getCommand().indexOf("EEB1110008000811")==0) {
				return true;
			}
		}
		return false;
	}

	@Override
	protected void handleMessage(MQMessageOfDAM msg) {
		try {
		 if(System.currentTimeMillis()-lastReceiveTime >MAX_TIME) {
			 this.clearData();
		 }
		 ScreenCommandEntity entity = (ScreenCommandEntity) msg.getAwsPostdata();
		 if(entity.getCommand().equals("EEB1110008000D100100")) {
			 this.isClickBtn = true;
		 }else if(entity.getCommand().indexOf("EEB1110008000411")==0) {
			 this.isReceiveRackName = true;
			 String rackNameCommand = entity.getCommand().replace("EEB1110008000411", "");
			 this.rackName = new String(ByteUtil.hexStringToBytes(rackNameCommand)).trim();
		 }
//		 else if(entity.getCommand().indexOf("")==0) {
//			 this.isReceiveDamDeviceCode = true;
//			 String damDeviceCodeCommand = entity.getCommand().replace("", "");
//			 this.damDeviceCode = new String(ByteUtil.hexStringToBytes(damDeviceCodeCommand)).trim();
//		 }
		 else if(entity.getCommand().indexOf("EEB1110008000611")==0) {
			 this.isReceiveCollectionDevice1Code = true;
			 String collectionDevice1CodeCommand = entity.getCommand().replace("EEB1110008000611", "");
			 this.collectionDevice1Code = new String(ByteUtil.hexStringToBytes(collectionDevice1CodeCommand)).trim();
		 }else if(entity.getCommand().indexOf("EEB1110008000811")==0) {
			 this.isReceiveCollectionDevice2Code = true;
			 String collectionDevice2CodeCommand = entity.getCommand().replace("EEB1110008000811", "");
			 this.collectionDevice2Code = new String(ByteUtil.hexStringToBytes(collectionDevice2CodeCommand)).trim();
		 }
		 
		 if(isClickBtn && isReceiveCollectionDevice1Code && isReceiveCollectionDevice2Code) {
			 Map<Short,String> map = new HashMap<>();
			 if(!rackName.equals("")&&!rackName.isEmpty()) {
				// 判断是否存在机柜
				ItAsset itAsset = damService.qryRackInfoByName(rackName);
				if(itAsset!=null) {   // 存在该机柜
					if(entity.getRackConverCode().equals(collectionDevice1Code)
							||entity.getRackConverCode().equals(collectionDevice2Code)
							||(collectionDevice1Code.equals(collectionDevice2Code)
									&&!collectionDevice1Code.isEmpty()
									&&!collectionDevice2Code.isEmpty())){
						map.put(DIALOG_ID, "硬件编码不能重复");
						sendCommandToScreen(entity.getRackConverCode(),map);
						return;
					}
					String result = insertOrUpdateDevice(itAsset.getId(),entity.getRackConverCode());
				
//					if(!collectionDevice1Code.equals("")
//						&&!collectionDevice1Code.isEmpty()) {
//						insertOrUpdateDevice(itAsset.getId(),collectionDevice1Code);
//					}
					
//					if(!collectionDevice2Code.equals("")
//						&&!collectionDevice2Code.isEmpty()) {
//						insertOrUpdateDevice(itAsset.getId(),collectionDevice2Code);
//					}
					map.put(DIALOG_ID, result);
					sendCommandToScreen(entity.getRackConverCode(),map);
					
				}else {
					// 未找到该机柜
					map.put(DIALOG_ID, "未查到该机柜");
					sendCommandToScreen(entity.getRackConverCode(),map);
				}
			}else{
				map.put(DIALOG_ID, "机柜不能为空");
				sendCommandToScreen(entity.getRackConverCode(),map);
			}
			 this.clearData();
		 }
		 
		 lastReceiveTime = System.currentTimeMillis();
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	private void sendCommandToScreen(String rackConverCode,Map<Short,String> map) throws Exception {
		IScreenCommandFactory rackScreenCommandFactroy = new UpdateArrayTextCommandFactory(rackConverCode, DIALOG_SCREEN_ID, map);
		ScreenCommandEntity sc =  rackScreenCommandFactroy.createScreenCommand();
		
		MQMessageOfDAM message = new MQMessageOfDAM();
		message.setActioncode(SEND_ACTION_CODE);
		message.setAwsPostdata(sc);
		message.setTimestamp(System.currentTimeMillis());
		
		String json = JSON.toJSONString(message);
		topicSender.send(TOPIC_NAME,json);
		logger.info("topic:{}  发送命令:{}",TOPIC_NAME,json);
		
		
		ScreenCommandEntity changeScreen =  rackScreenCommandFactroy.changeScreenCommand();
		
		MQMessageOfDAM msg = new MQMessageOfDAM();
		msg.setActioncode(SEND_ACTION_CODE);
		msg.setAwsPostdata(changeScreen);
		msg.setTimestamp(System.currentTimeMillis());
		
		String changeScreenJson = JSON.toJSONString(msg);
		topicSender.send(TOPIC_NAME,changeScreenJson);
		logger.info("topic:{}  发送命令:{}",TOPIC_NAME,changeScreenJson);
		
	}

	private String insertOrUpdateDevice(long rackId,String rackConverCode) throws Exception {
		DeviceType damDevice = damService.qryDamDeviceByRackId(rackId);
		if(damDevice!=null&&!damDevice.getRackConverCode().trim().equals(rackConverCode)) {
			return "该机柜已绑定了编号为["+damDevice.getRackConverCode()+"]的dam设备";
		}
		
		damService.deleteDeviceByRackIdAndRackConverCode(rackConverCode);
		
		
//		DeviceTypeVo deviceTypeVo = damService.qryDamDevice(rackConverCode);
		DeviceType deviceType = new DeviceType();
		deviceType.setAssetId(rackId);
		deviceType.setRackConverCode(rackConverCode);
		deviceType.setId(IdWorker.getId());
		deviceType.setIp("0.0.0.0");
		deviceType.setOnlineTime(new Date());
		deviceType.setType(2);
		damService.insertDevice(deviceType);
		
		// 插入扩展设备
		if(!collectionDevice1Code.equals("")||!collectionDevice1Code.isEmpty()) {
			deviceType.setId(IdWorker.getId());
			deviceType.setRackConverCode(collectionDevice1Code);
			deviceType.setType(1);
			damService.insertDevice(deviceType);
		}
		if(!collectionDevice2Code.equals("")||!collectionDevice2Code.isEmpty()) {
			deviceType.setId(IdWorker.getId());
			deviceType.setRackConverCode(collectionDevice2Code);
			deviceType.setType(1);
			damService.insertDevice(deviceType);
		}
		
		return "绑定成功";
		
//		if(deviceTypeVo!=null) {
//			damService.updateDevice(deviceType);
//		}else {
//			deviceType.setId(IdWorker.getId());
//			deviceType.setIp("0.0.0.0");
//			deviceType.setOnlineTime(new Date());
//			deviceType.setType(2);
//			damService.insertDevice(deviceType);
//		}
	}
	
	private void clearData() {
		isClickBtn = false;
		isReceiveRackName = false;
		isReceiveDamDeviceCode = false;
		isReceiveCollectionDevice1Code = false;
		isReceiveCollectionDevice2Code = false;
		
		rackName = "";
		damDeviceCode = "";
		collectionDevice1Code = "";
		collectionDevice2Code = "";
	}
}
